package com.eric.utils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class ListUtils {
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static void printList (Object c) {
		if (c instanceof List) {
			for (Object o : (List)c) {
				System.out.println(o.toString());
			}
		}else if (c instanceof Map) {
			for (Entry<Object, Integer> o : ((Map<Object,Integer>)c).entrySet()) {
				System.out.println(o.getKey()+"="+o.getValue());
			}
		}
		
	}
	
	public static Map<Object,Integer> countDistinct (List<? extends Object> list) {
		Map<Object,Integer> map = new HashMap<>();
		
		for (Object o : list) {
			if (map.containsKey(o)) {
				Integer c = map.get(o);
				c = c + 1;
				map.put(o, c);
			}else{
				map.put(o, 1);
			}
		}
		return map;
	}
	
	public static String listToString(List<String> stringList){
        if (stringList==null) {
            return null;
        }
        StringBuilder result=new StringBuilder();
        boolean flag=false;
        for (String string : stringList) {
            if (flag) {
                result.append(",");
            }else {
                flag=true;
            }
            result.append(string);
        }
        return result.toString();
    }
	
    public static Map<Object, Integer> sortMapByValue(Map<Object, Integer> oriMap) {  
        Map<Object, Integer> sortedMap = new LinkedHashMap<>();  
        if (oriMap != null && !oriMap.isEmpty()) {  
            List<Map.Entry<Object, Integer>> entryList = new ArrayList<Map.Entry<Object, Integer>>(oriMap.entrySet());  
            Collections.sort(entryList,  
                    new Comparator<Map.Entry<Object, Integer>>() {  
                        public int compare(Entry<Object, Integer> entry1,  
                                Entry<Object, Integer> entry2) {  
                            int value1 = 0, value2 = 0;  
                            try {  
                                value1 = entry1.getValue();  
                                value2 = entry2.getValue();  
                            } catch (NumberFormatException e) {  
                                value1 = 0;  
                                value2 = 0;  
                            }  
                            return value2 - value1;  
                        }  
                    });  
            Iterator<Map.Entry<Object, Integer>> iter = entryList.iterator();  
            Map.Entry<Object, Integer> tmpEntry = null;  
            while (iter.hasNext()) {  
                tmpEntry = iter.next();  
                sortedMap.put(tmpEntry.getKey(), tmpEntry.getValue());  
            }  
        }  
        return sortedMap;  
    }  
}
